package com.hzgj.bcl.soa.rpc.server;

import com.hzgj.bcl.util.jmx.annotation.MBean;
import com.hzgj.bcl.util.jmx.annotation.ManagedAttribute;
import com.hzgj.bcl.util.jmx.annotation.ManagedOperation;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import lombok.Getter;
import lombok.Setter;

/**
 * Created by ye.pan on 2015/5/29.
 */
@ChannelHandler.Sharable
@MBean(description = "connection handler")
public class ConnectionHandler extends ChannelInboundHandlerAdapter {

    @Setter
    @Getter
    @ManagedAttribute(description = "max number of connected client", writable = true)
    private int max_connections;

    private ChannelGroup allChannels;

    public ConnectionHandler(ChannelGroup allChannels) {
        this.allChannels = allChannels;
    }

    @ManagedOperation(description = "number of connected clients")
    public int getConnections() {
        return allChannels.size();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        allChannels.add(ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        allChannels.remove(ctx.channel());
        super.channelInactive(ctx);
    }
}
